<template>
  <el-container style="height: 100vh;">
    <!-- 左侧导航栏 -->
    <el-aside :width="sideWidth + 'px'" style="background-color: rgb(238, 241, 246)">
      <Sidebar />
    </el-aside>

    <!-- 右侧内容 -->
    <el-container>
      <!-- 页面主体 -->
      <el-main style="padding: 10px">
        <div class="grid-table-container">
          <el-card class="box-card">
            <!-- 字段说明 -->
            <div class="field-description" style="margin-bottom: 20px; color: #666; font-size: 12px;">
              <p>字段说明：</p>
              <ul>
                <li><strong>表名</strong> - videos</li>
                <li><strong>Author</strong> - 视频作者</li>
                <li><strong>Comment</strong> - 视频描述</li>
                <li><strong>Likes</strong> - 点赞数</li>
                <li><strong>Favorites</strong> - 收藏数</li>
                <li><strong>Shares</strong> - 分享数</li>
                <li><strong>Duration</strong> - 视频时长</li>
                <li><strong>Category</strong> - 视频分类</li>
              </ul>
            </div>
            <!-- SQL输入框 -->
            <el-input
                type="textarea"
                :autosize="{ minRows: 5, maxRows: 10 }"
                placeholder="请输入SQL查询语句"
                v-model="sql"
            />

            <!-- 操作按钮 -->
            <div style="margin-top: 20px; border-top: 1px solid #E8E8E8;">
              <el-form :inline="true" class="demo-form-inline" style="margin-left: 10px; margin-top: 20px">
                <el-form-item>
                  <el-button type="primary" @click="onSubmit">查询</el-button>
                </el-form-item>
                <el-form-item>
                  <el-button type="info" plain @click="onReset">重置</el-button>
                </el-form-item>
              </el-form>
            </div>

            <!-- 数据表格 -->
            <el-table
                :data="tableData"
                style="width: 100%"
                border
            >
              <el-table-column
                  v-for="column in columns"
                  :key="column.field"
                  :prop="column.field"
                  :label="column.label"
                  align="center"
                  header-align="center"
              ></el-table-column>
            </el-table>

            <!-- 题目展示区 -->
            <div class="question-area">
              <h3 class="section-title">SQL练习题</h3>
              <div
                  v-for="(item, index) in questions"
                  :key="index"
                  class="question-item"
              >
                <div class="question-title">题目{{ index + 1 }}：{{ item.question }}</div>
                <el-input
                    class="question-input"
                    type="textarea"
                    :autosize="{ minRows: 2, maxRows: 4 }"
                    placeholder="请输入SQL语句"
                    v-model="userAnswers[index]"
                />
                <div v-if="results[index]" :style="{ color: results[index].correct ? 'green' : 'red' }">
                  {{ results[index].correct ? '回答正确' : '回答错误' }}
                  <span v-if="!results[index].correct">，正确答案：{{ results[index].correctAnswer }}</span>
                </div>
              </div>
            </div>

            <!-- 提交按钮 -->
            <div style="margin-top: 20px; text-align: center">
              <el-button type="primary" @click="submitAnswers">提交答案</el-button>
            </div>

            <!-- 分数显示 -->
            <div v-if="score !== null" style="margin-top: 20px; text-align: center; font-size: 18px;">
              总分：{{ score*5 }} / {{ totalQuestions*5 }}
            </div>
          </el-card>
        </div>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import axios from "axios";
import { ElMessage } from "element-plus";
import Sidebar from "@/views/Sidebar.vue";

export default {
  components: { Sidebar },
  data() {
    return {
      sql: "",
      tableData: [],
      columns: [],
      questions: [],
      sideWidth: 200,
      userAnswers: [],
      score: null,
      results: []
    };
  },
  computed: {
    totalQuestions() {
      return Array.isArray(this.questions) ? this.questions.length : 0;
    }
  },
  methods: {
    onSubmit() {
      axios({
        method: "get",
        url: "http://localhost:80/onlineSql2",
        params: {sql2: this.sql},
      })
          .then((response) => {
            if (!response.data || response.data.length === 0) {
              // ElMessage.warning("查询结果为空或SQL语句有误");
              this.tableData = [];
            } else {
              this.tableData = response.data;
              if (this.tableData.length > 0) {
                const firstRow = this.tableData[0];
                const validKeys = Object.keys(firstRow).filter(key => firstRow[key] !== null);
                this.columns = validKeys.map(key => ({
                  field: key,
                  label: key.charAt(0).toUpperCase() + key.slice(1),
                }));
              }
            }
            this.$nextTick(() => {
              console.log("DOM 更新完成");
            });
          })
          .catch((error) => {
            console.error("查询失败", error);
            ElMessage.error("查询执行失败");
          });
    },

    onReset() {
      this.sql = "";
      this.tableData = [];
      this.columns = [];
    },

    submitAnswers() {
      let correctCount = 0;
      this.results = [];

      for (let i = 0; i < this.questions.length; i++) {
        const userAnswer = this.userAnswers[i]?.trim().toLowerCase() || "";
        const correctAnswer = this.questions[i].answer.trim().toLowerCase();

        const isCorrect = userAnswer === correctAnswer;
        if (isCorrect) {
          correctCount++;
        }

        this.results.push({
          correct: isCorrect,
          userAnswer: userAnswer,
          correctAnswer: correctAnswer
        });
      }

      this.score = correctCount;
    }
  },
  mounted() {
    this.questions = [
      {
        question: "1. 查询所有视频的作者和分类",
        answer: "SELECT Author, Category FROM videos"
      },
      {
        question: "2. 查找旅游分类下点赞过万的视频名称和作者",
        answer: "SELECT Author,Comment FROM videos WHERE Category = '旅游' AND Likes > 10000"
      },
      {
        question: "3. 查询知识分类下的所有视频的作者和分类",
        answer: "SELECT Author, Category FROM videos WHERE Category = '知识'"
      },
      {
        question: "4. 查询点赞数大于10000的视频的作者和点赞数",
        answer: "SELECT Author, Likes FROM videos WHERE Likes > 10000"
      },
      {
        question: "5. 查询收藏数在1000到5000之间的视频的作者和收藏数",
        answer: "SELECT Author, Favorites FROM videos WHERE Favorites BETWEEN 1000 AND 5000"
      },
      {
        question: "6. 查询点赞数大于分享数的视频的作者和点赞数",
        answer: "SELECT Author, Likes FROM videos WHERE Likes > Shares"
      },
      {
        question: "7. 查询视频描述中包含“美食”的视频的作者和视频描述",
        answer: "SELECT Author, Comment FROM videos WHERE Comment LIKE '%美食%'"
      },
      {
        question: "8. 查询分类为“游戏”且点赞数大于5000的视频的作者和点赞数",
        answer: "SELECT Author, Likes FROM videos WHERE Category = '游戏' AND Likes > 5000"
      },
      {
        question: "9. 查询收藏数大于点赞数的视频的作者和收藏数",
        answer: "SELECT Author, Favorites FROM videos WHERE Favorites > Shares"
      },
      {
        question: "10. 查询分类为“旅游”且收藏数大于500的视频的作者和分类",
        answer: "SELECT Author, Category FROM videos WHERE Category = '旅游' AND Favorites > 500"
      },
      {
        question: "11. 查询收藏数大于分享数且分类为“知识”的视频的作者和收藏数",
        answer: "SELECT Author, Favorites FROM videos WHERE Favorites > Shares AND Category = '知识'"
      },
      {
        question: "12. 查询视频描述中包含“教学”的视频的作者和视频描述",
        answer: "SELECT Author, Comment FROM videos WHERE Comment LIKE '%教学%'"
      },
      {
        question: "13. 查询视频描述中包含“人工智能”的视频的作者和视频描述",
        answer: "SELECT Author, Comment FROM videos WHERE Comment LIKE '%人工智能%'"
      },
      {
        question: "14. 查询分享数大于1000且分类为“游戏”的视频的作者和分享数",
        answer: "SELECT Author, Shares FROM videos WHERE Shares > 1000 AND Category = '游戏'"
      },
      {
        question: "15. 查询视频描述中包含“旅行”的视频的作者和视频描述",
        answer: "SELECT Author, Comment FROM videos WHERE Comment LIKE '%旅行%'"
      },
      {
        question: "16. 将分类为“知识”的视频的点赞数增加1000",
        answer: "UPDATE videos SET Likes = Likes + 1000 WHERE Category = '知识'"
      },
      {
        question: "17. 将分类为“游戏”的视频的分享数减少200",
        answer: "UPDATE videos SET Shares = Shares - 200 WHERE Category = '游戏'"
      },
      {
        question: "18. 将分类为“美食”的视频的收藏数增加500",
        answer: "UPDATE videos SET Favorites = Favorites + 500 WHERE Category = '美食'"
      },
      {
        question: "19. 删除分类为“旅游”且点赞数小于1000的视频",
        answer: "DELETE FROM videos WHERE Category = '旅游' AND Likes < 1000"
      },
      {
        question: "20. 删除分类为“美食”且收藏数小于500的视频",
        answer: "DELETE FROM videos WHERE Category = '美食' AND Favorites < 500"
      }
    ];

    this.userAnswers = new Array(this.questions.length).fill("");
  }
};
</script>

<style scoped>
/* 新增全局高度设置 */
html, body, #app {
  height: 100%;
  margin: 0;
}

/* 修改容器布局 */
.el-container {
  height: 100vh;
  flex-direction: row; /* 确保布局方向为水平 */
}

/* 调整主内容区 */
.el-main {
  flex: 1;
  padding: 0 !important; /* 移除默认padding */
  display: flex;
  flex-direction: column;
}

.grid-table-container {
  flex: 1;
  display: flex;
  padding: 20px;
  width: 100%;
}

.box-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  width: 100%;
}

/* 表格容器自适应 */
.el-table {
  flex: 1;
  margin-top: 20px;
}

/* 题目区域样式 */
.question-area {
  margin-bottom: 20px;
}

.question-item {
  margin-bottom: 20px;
  border-bottom: 1px solid #e8e8e8;
  padding-bottom: 20px;
}

.question-title {
  font-weight: bold;
  margin-bottom: 10px;
}

.sql-answer {
  background-color: #f5f5f5;
  padding: 10px;
  margin-bottom: 10px;
  font-family: monospace;
  white-space: pre-wrap;
}

.question-input {
  width: 100%;
  margin-bottom: 10px;
}
</style>
